﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using OnlineVideos.Data;
using System.Windows.Media.Imaging;
using System.Collections.Generic;
using System.Linq;
using OnlineVideos.Common;
using System.Windows.Threading;
using Common.Library;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Linq;
using System.Windows.Resources;
using OnlineVideos.Entities;
using System.Threading.Tasks;

//using Common.Common;

namespace OnlineVideos.UI
{
    public static class StoryReadingExperience
    {
        static DispatcherTimer buttonTimer = new DispatcherTimer();
        public static StackPanel messagestack = null;
        public static Image imgRight = null;
        public static Image ResumeButton = null;
        static Canvas can = new Canvas();
        static long begin = 0;
        static long end = 0;
        public static IDictionary<string, string> storyDictionary = null;
        public static string Image1 = string.Empty;
        static int RowCount = 0;

        public static int storystackmanipulationCompleted(Image imgstory, TextBlock txtpara, TextBlock txtpageno, int pagenum, Grid dummygrid, MediaElement mymedia, bool buttontapped)
        {
            RetriveFromStorage(imgstory, txtpara, txtpageno, pagenum, dummygrid, mymedia, buttontapped);
            return 0;
        }

        public static int storystackmanipulationdelta(ManipulationDeltaEventArgs e, int pagenumber, int slidestatus, StackPanel stk)
        {

            if (e == null)
            {

                if (pagenumber != storyDictionary.Count)
                {
                    pagenumber = ++pagenumber;
                    animatepage("Left", stk);

                }

            }
            else
            {

                if (e.DeltaManipulation.Translation.X < 0)
                {
                    if (pagenumber != storyDictionary.Count)
                    {
                        pagenumber = ++pagenumber;
                        animatepage("Left", stk);
                    }

                }

                if (e.DeltaManipulation.Translation.X > 0)
                {
                    if (pagenumber != 1)
                    {
                        pagenumber = --pagenumber;
                        animatepage("Right", stk);
                    }


                }
            }
            return pagenumber;
        }
        public static void animatepage(string direction, StackPanel mainstk)
        {

            Storyboard flip = new Storyboard();
            DoubleAnimation animation = new DoubleAnimation()
            {
                Duration = new TimeSpan(0, 0, 0, 0, 500)
            };
            flip.Children.Add(animation);
            if (direction == "Left")
            {
                if (mainstk.Projection == null)
                {

                    mainstk.Projection = new PlaneProjection()
                    {
                        CenterOfRotationX = -0.01
                    };
                }
                PlaneProjection projection = mainstk.Projection as PlaneProjection;

                if (projection.GlobalOffsetX == 0)
                {
                    animation.From = 460;
                    animation.To = 0;

                }
                else
                {
                    animation.From = 460;
                    animation.To = 0;
                }
                Storyboard.SetTarget(animation, projection);
            }
            else if (direction == "Right")
            {
                if (mainstk.Projection == null)
                {
                    mainstk.Projection = new PlaneProjection()
                    {
                        CenterOfRotationX = -0.01
                    };
                }

                PlaneProjection projection = mainstk.Projection as PlaneProjection;
                if (projection.GlobalOffsetX == 0)
                {
                    animation.From = -460;
                    animation.To = 0;
                }
                else
                {
                    animation.From = -460;
                    animation.To = 0;
                }
                Storyboard.SetTarget(animation, projection);
            }

            Storyboard.SetTargetProperty(animation,
              new PropertyPath(PlaneProjection.GlobalOffsetXProperty));

            flip.Begin();
        }

        public static void storystackmouseenter(StackPanel Resume)
        {
            Resume.Visibility = Visibility.Visible;

            //messagestack = Resume;
            //buttonTimer.Interval = TimeSpan.FromSeconds(5);
            //buttonTimer.Tick += new EventHandler(buttonTimer_Tick);
            //buttonTimer.Start();
        }
        static void buttonTimer_Tick(object sender, EventArgs e)
        {

            //messagestack.Visibility = Visibility.Collapsed;
            //buttonTimer.Stop();
        }
        public static void DivideRowsasperViewableArea(string description, string image, double font, Grid dummygrid)
        {
            try
            {
                string[] currentrow = new string[2];
                string Text = string.Empty;
                double controlheight = 0;
                TextBlock proto = new TextBlock();
                proto.FontSize = font;
                if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                {
                    proto.FontFamily = new FontFamily("/COM4NRG_.TTF#COM4t Nuvu Regular");
                }
                proto.Width = 440;
                proto.Margin = new Thickness(1000, 1000, 0, 0);
                proto.TextWrapping = TextWrapping.Wrap;
                proto.Text = description;
                dummygrid.Children.Add(proto);
                dummygrid.UpdateLayout();
                Image1 = image;
                if (image == "")
                {
                    ShowList objlist = new ShowList();
                    objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);
                    if (objlist.SubTitle == Constants.MovieCategoryTelugu || objlist.SubTitle == Constants.MovieCategoryHindi)
                    {
                        controlheight = 580; ;
                    }
                    else
                    {
                        controlheight = 590;
                    }

                }
                else
                {
                    if (proto.RenderSize.Height > 590)
                    {
                        ShowList objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);
                        if (objlist.SubTitle == Constants.MovieCategoryTelugu || objlist.SubTitle == Constants.MovieCategoryHindi)
                        {
                            controlheight = 580;
                            image = "";
                        }
                        else
                        {
                            controlheight = 590;
                            image = "";
                        }
                    }
                    else
                    {
                        controlheight = 300;
                        image = Image1;
                    }
                }
                if (controlheight < proto.RenderSize.Height)
                {
                    while (controlheight < proto.RenderSize.Height)
                    {
                        Text = proto.Text.Substring(0, proto.Text.LastIndexOf(' '));
                        proto.Text = Text;
                        dummygrid.UpdateLayout();
                    }

                    if (image == Image1)
                    {
                        storyDictionary.Add(Text, image);
                        Image1 = "";

                    }
                    else
                    {
                        storyDictionary.Add(Text, image);
                    }
                    if (description.Substring(Text.Length).Length > 0)
                    {
                        ShowList objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);
                        if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryTelugu)
                        {
                            DivideRowsasperViewableArea(description.Substring(Text.Length), Image1, 31, dummygrid);

                        }
                        if (objlist.SubTitle == Constants.MovieCategoryEnglish)
                        {
                            if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                            {
                                DivideRowsasperViewableArea(description.Substring(Text.Length), Image1, 34, dummygrid);
                            }
                            else
                            {
                                DivideRowsasperViewableArea(description.Substring(Text.Length), Image1, 24, dummygrid);
                            }

                        }
                        if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryHindi)
                        {
                            DivideRowsasperViewableArea(description.Substring(Text.Length), Image1, 26, dummygrid);
                        }

                    }
                }
                else
                {
                    RowCount++;

                    if (RowCount < StoryManager.MaxRows(AppSettings.ShowUniqueID.ToString(), 1) + 1)
                    {

                        currentrow = StoryManager.ReadFromDatabase(AppSettings.ShowUniqueID.ToString(), RowCount, 1);
                        if (Image1 != "")
                        {
                            storyDictionary.Add(proto.Text, Image1);
                            proto.Text = "";

                        }
                        ShowList objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);
                        if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryTelugu)
                        {
                            DivideRowsasperViewableArea(proto.Text + Environment.NewLine + currentrow[0].ToString(), currentrow[1].ToString(), 31, dummygrid);

                        }
                        if (objlist.SubTitle == Constants.MovieCategoryEnglish)
                        {
                            if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                            {
                                DivideRowsasperViewableArea(proto.Text + Environment.NewLine + "                    " + currentrow[0].ToString(), currentrow[1].ToString(), 34, dummygrid);
                            }
                            else
                            {
                                DivideRowsasperViewableArea(proto.Text + Environment.NewLine + "                    " + currentrow[0].ToString(), currentrow[1].ToString(), 24, dummygrid);
                            }

                        }
                        if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryHindi)
                        {
                            DivideRowsasperViewableArea(proto.Text + Environment.NewLine + currentrow[0].ToString(), currentrow[1].ToString(), 26, dummygrid);
                        }
                    }
                    else
                    {
                        if (proto.RenderSize.Height > 300)
                        {
                            storyDictionary.Add(proto.Text, "");
                            storyDictionary.Add("", "End-marker.png");
                        }
                        else
                        {
                            storyDictionary.Add(proto.Text, "End-marker.png");
                        }
                    }
                }

                dummygrid.Children.Remove(proto);
            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in DivideRowsasperViewableArea Method In StoryReadingExperience.cs file", ex);
            }

        }
        public static void StartRetriving(Grid dummygrid)
        {
            try
            {
                storyDictionary = new Dictionary<string, string>();
                string[] firstRecord = new string[2];

                for (RowCount = 1; RowCount < StoryManager.MaxRows(AppSettings.ShowUniqueID.ToString(), 1) + 1; RowCount++)
                {
                    firstRecord = StoryManager.ReadFromDatabase(AppSettings.ShowUniqueID.ToString(), RowCount, 1);

                    ShowList objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);

                    if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryTelugu)
                    {
                        DivideRowsasperViewableArea(firstRecord[0].ToString(), firstRecord[1].ToString(), 31, dummygrid);

                    }
                    if (objlist.SubTitle == Constants.MovieCategoryEnglish)
                    {
                        if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                        {
                            DivideRowsasperViewableArea(firstRecord[0].ToString(), firstRecord[1].ToString(), 34, dummygrid);
                        }
                        else
                        {
                            DivideRowsasperViewableArea(firstRecord[0].ToString(), firstRecord[1].ToString(), 24, dummygrid);
                        }

                    }
                    if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryHindi)
                    {
                        DivideRowsasperViewableArea(firstRecord[0].ToString(), firstRecord[1].ToString(), 26, dummygrid);
                    }


                }
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in StartRetriving Method In StoryReadingExperience.cs file", ex);
            }
        }
        public static IsolatedStorageFileStream Trimstoryvoice(int start, int end)
        {
            try
            {
                IsolatedStorageFileStream output = default(IsolatedStorageFileStream);
                MemoryStream sfd = new MemoryStream();
                var userStore = IsolatedStorageFile.GetUserStoreForApplication();

                if (userStore.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav"))
                {
                    using (IsolatedStorageFileStream fs = userStore.OpenFile("/StoryRecordings/" + AppSettings.ShowID + "/" + AppSettings.Title + ".wav", FileMode.Open, FileAccess.ReadWrite))
                    {
                        fs.CopyTo(sfd);
                        output = userStore.OpenFile("story.wav", FileMode.Create);
                        byte[] readBuffer = new byte[4096];
                        int bytesRead = -1;
                        sfd.Position = start;
                        sfd.SetLength(end);
                        WriteWavHeader(output, 16000);
                        while ((bytesRead = sfd.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            output.Write(readBuffer, 0, bytesRead);
                        }
                        fs.Dispose();
                        fs.Close();
                        UpdateWavHeader(output);
                        output.Position = 0;
                    }
                }

                return output;
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in Trimstoryvoice Method In StoryReadingExperience.cs file", ex);
                 return null;
            }
        }
        public static void UpdateWavHeader(Stream stream)
        {
            try
            {
                var oldPos = stream.Position;
                stream.Seek(4, SeekOrigin.Begin);
                stream.Write(BitConverter.GetBytes((int)stream.Length - 8), 0, 4);
                stream.Seek(40, SeekOrigin.Begin);
                stream.Write(BitConverter.GetBytes((int)stream.Length - 44), 0, 4);
                stream.Seek(oldPos, SeekOrigin.Begin);

            }
            catch (Exception ex)
            {
                
                 Exceptions.SaveOrSendExceptions("Exception in UpdateWavHeader Method In StoryReadingExperience.cs file", ex);
            }
        }
        public static void WriteWavHeader(Stream stream, int sampleRate)
        {
            try
            {
                const int bitsPerSample = 16;
                const int bytesPerSample = bitsPerSample / 8;
                var encoding = System.Text.Encoding.UTF8;
                stream.Write(encoding.GetBytes("RIFF"), 0, 4);
                stream.Write(BitConverter.GetBytes(0), 0, 4);
                stream.Write(encoding.GetBytes("WAVE"), 0, 4);
                stream.Write(encoding.GetBytes("fmt "), 0, 4);
                stream.Write(BitConverter.GetBytes(16), 0, 4);
                stream.Write(BitConverter.GetBytes((short)1), 0, 2);
                stream.Write(BitConverter.GetBytes((short)1), 0, 2);
                stream.Write(BitConverter.GetBytes(sampleRate), 0, 4);
                stream.Write(BitConverter.GetBytes(sampleRate * bytesPerSample), 0, 4);
                stream.Write(BitConverter.GetBytes((short)(bytesPerSample)), 0, 2);
                stream.Write(BitConverter.GetBytes((short)(bitsPerSample)), 0, 2);
                stream.Write(encoding.GetBytes("data"), 0, 4);
                stream.Write(BitConverter.GetBytes(0), 0, 4);
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in WriteWavHeader Method In StoryReadingExperience.cs file", ex);
            }
        }
        public static void RetriveFromStorage(Image imgstory, TextBlock txtPara, TextBlock txtpageno, int pagenum, Grid dummygrid, MediaElement mymedia, bool buttontapped)
        {
            try
            {
                txtpageno.Text = (pagenum).ToString() + "/" + (storyDictionary.Count).ToString();

                if (mymedia != null && Constants.mode == "Listen")
                {

                    if (Task.Run(async () => await Storage.FileExists("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml")).Result)
                    {
                        XDocument xdoc = Storage.ReadFileAsDocument("/StoryRecordings/" + AppSettings.ShowID + "/StoryRecordings.xml");

                        var data = from f in xdoc.Descendants("Stories").Elements("Story")
                                   where (Convert.ToInt32(f.Attribute("Id").Value)) == pagenum
                                   select f;
                        if (data.Count() > 0)
                        {
                            foreach (var d in data)
                            {

                                mymedia.SetSource(Trimstoryvoice(Convert.ToInt32(d.Element("Begin").Value), Convert.ToInt32(d.Element("End").Value)));
                                if (buttontapped == false)
                                {
                                    mymedia.AutoPlay = true;
                                    mymedia.Play();
                                }
                                else
                                    mymedia.AutoPlay = false;
                            }

                        }
                        else
                        {
                            mymedia.Source = null;
                        }

                    }

                    else
                    {
                        mymedia.Source = null;
                    }
                }
                else
                {
                    if (Constants.mode == "Listenmp3")
                    {

                        XDocument xmlDoc =
                    XDocument.Load("Story Reading Xml/StoryReading.xml");
                        var findEle = from i in xmlDoc.Descendants("show") where i.Attribute("id").Value.ToString() == AppSettings.ShowID select i;
                        var data = from f in findEle.Descendants("story")
                                   where (Convert.ToInt32(f.Attribute("id").Value)) == pagenum
                                   select f;
                        if (data.Count() > 0)
                        {
                            foreach (var d in data)
                            {
                                mymedia.Markers.Clear();
                                Constants.StartPosition = Convert.ToInt32(d.Element("begintime").Value);
                                IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
                                string title = StoryManager.GetTitle(AppSettings.ShowUniqueID);
                                if (Constants.Downloadedstream != default(Stream))
                                {
                                    long RequiredSize = Constants.Downloadedstream.Length;
                                    byte[] SaveFile = new byte[RequiredSize];

                                    if (!Task.Run(async () => await Storage.FileExists(title + ".mp3")).Result)
                                    {
                                        IsolatedStorageFileStream isoFile = new IsolatedStorageFileStream(title + ".mp3", System.IO.FileMode.Create, isoStore);
                                        Constants.Downloadedstream.Read(SaveFile, 0, SaveFile.Length);
                                        isoFile.Write(SaveFile, 0, SaveFile.Length);
                                        isoFile.Close();

                                    }
                                }

                                var isfs = new IsolatedStorageFileStream(title + ".mp3", FileMode.Open, isoStore);
                                mymedia.SetSource(isfs);
                                Constants.EndPosition = Convert.ToInt32(d.Element("endtime").Value);
                                mymedia.Play();
                                isfs.Close();



                            }
                        }
                        else
                        {
                            mymedia.Source = null;
                        }
                    }

                }



                if (pagenum == 1)
                {
                    txtPara.Text = "";
                    Run runLabel = new Run();
                    runLabel.FontSize = 44;
                    runLabel.Text = "                    " + storyDictionary.ElementAt(pagenum - 1).Key.Substring(0, 1);
                    Run runLabel1 = new Run();

                    ShowList objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);
                    if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryTelugu)
                    {
                        runLabel1.FontSize = 31;
                    }
                    if (objlist.SubTitle == Constants.MovieCategoryEnglish)
                    {
                        if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                        {
                            runLabel1.FontSize = 34;
                        }
                        else
                        {
                            runLabel1.FontSize = 24;
                        }
                    }
                    if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryHindi)
                    {
                        runLabel1.FontSize = 26;
                    }
                    runLabel1.Text = storyDictionary.ElementAt(pagenum - 1).Key.Substring(1);
                    txtPara.Inlines.Add(runLabel);
                    txtPara.Inlines.Add(runLabel1);
                }
                else
                {
                    txtPara.Text = storyDictionary.ElementAt(pagenum - 1).Key;
                }


                if (storyDictionary.ElementAt(pagenum - 1).Value != "")
                {
                    TextBlock proto = new TextBlock();
                    ShowList objlist = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID);
                    if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryTelugu)
                    {
                        proto.FontSize = 31;
                    }
                    if (objlist.SubTitle == Constants.MovieCategoryEnglish)
                    {
                        if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                        {
                            proto.FontSize = 34;
                        }
                        else
                        {
                            proto.FontSize = 24;
                        }
                    }
                    if (ResourceHelper.AppName == Apps.Vedic_Library.ToString() && objlist.SubTitle == Constants.MovieCategoryHindi)
                    {
                        proto.FontSize = 26;
                    }
                    if (ResourceHelper.AppName == Apps.Story_Time.ToString())
                    {
                        proto.FontFamily = new FontFamily("/COM4NRG_.TTF#COM4t Nuvu Regular");
                    }
                    proto.Width = 440;
                    proto.Margin = new Thickness(1000, 1000, 0, 0);
                    proto.TextWrapping = TextWrapping.Wrap;
                    proto.Text = txtPara.Text;
                    dummygrid.Children.Add(proto);
                    dummygrid.UpdateLayout();
                    if (proto.RenderSize.Height < 100)

                        imgstory.Margin = new Thickness(06, 160, 10, 10);
                    else
                        imgstory.Margin = new Thickness(06, 18, 10, 10);

                    imgstory.Visibility = Visibility.Visible;
                    if (storyDictionary.ElementAt(pagenum - 1).Value.ToString() != "End-marker.png")
                    {
                        Constants.UIThread = true;
                        imgstory.Source = ResourceHelper.getStoryImageFromStorageOrInstalledFolderForWp8(storyDictionary.ElementAt(pagenum - 1).Value);
                        Constants.UIThread = false;
                    }
                    else
                        imgstory.Source = new BitmapImage(new Uri("/Images/storyImages/" + storyDictionary.ElementAt(pagenum - 1).Value, UriKind.Relative));

                }
                else
                {
                    //txtPara.Height = 590;

                    imgstory.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                
                   Exceptions.SaveOrSendExceptions("Exception in RetriveFromStorage Method In StoryReadingExperience.cs file", ex);
            }

        }
    }
}
